package com.bjtu.ptsite.mapper;

import com.baomidou.mybatisplus.annotation.TableName;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.bjtu.ptsite.model.PeerMessage;
import org.apache.ibatis.annotations.*;

import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;

@Mapper
public interface PeerMapper extends BaseMapper<PeerMessage> {
    String TABLE_NAME = "bt_peer_info";

    @Select("SELECT * FROM " + TABLE_NAME  + " WHERE peer_id = #{peerId}")
    PeerMessage selectByPeerId(String peerId);

    @Select("""
        SELECT * FROM bt_peer_info 
        WHERE pass_key = #{passKey}
          AND info_hash = #{infoHash}
          AND peer_id = #{peerId}
          AND ip = #{ip}
          AND port = #{port}
        LIMIT 1
    """)
    PeerMessage selectByPassKey(String passKey, String infoHash, String peerId, String ip, int port);

    @Insert("INSERT INTO " +
             TABLE_NAME +
            " (peer_id, uploaded, downloaded, peer_left, port, ip, last_announce_time, event, pass_key, info_hash, seeder ) VALUES " +
            "(#{peerId}, #{uploaded}, #{downloaded}, #{peerLeft}, #{port}, #{ip}, #{lastAnnounceTime}, #{event}, #{passkey}, #{infoHash}, #{isSeeder})")
    void insertPeerMessage(PeerMessage peerMessage);

    @Update("UPDATE " +
             TABLE_NAME +
            " SET uploaded = #{uploaded}, downloaded = #{downloaded}, peer_left = #{peerLeft}, port = #{port}, ip = #{ip}, last_announce_time = #{lastAnnounceTime}, event = #{event} ,seeder =#{isSeeder} " +
            " WHERE id=#{id} ")
    void updatePeerMessage(PeerMessage peerMessage);


    @Select("SELECT * FROM " +
            TABLE_NAME +
            " WHERE info_hash = #{infoHash} AND last_announce_time > #{fiveMinutesAgo} and (event IS NULL OR event != 'stopped') and peer_left=0 ")
    List<PeerMessage> selectPeerMessageList(String infoHash, Date fiveMinutesAgo);

    @Delete("DELETE FROM " + TABLE_NAME + " WHERE #{id} IS NULL OR id = #{id}")
    void delete(Integer id);

    @Select("SELECT COUNT(*) FROM " + TABLE_NAME + " WHERE #{infoHash} IS NULL OR info_hash = #{infoHash}")
    int selectCount(String infoHash);

    @Insert("INSERT INTO " +
            TABLE_NAME +
            " (id, peer_id, uploaded, downloaded, peer_left, port, ip, last_announce_time, event, pass_key, info_hash, seeder ) VALUES " +
            "(#{id}, #{peerId}, #{uploaded}, #{downloaded}, #{peerLeft}, #{port}, #{ip}, #{lastAnnounceTime}, #{event}, #{passkey}, #{infoHash}, #{isSeeder})")
    void insertPeerMessage2(PeerMessage peerMessage);

    @Select("SELECT * FROM " + TABLE_NAME + " WHERE info_hash = #{infoHash} and peer_left =0 and (event != 'stopped' or event is null) ")
    List<PeerMessage> selectByInfoHash(String infoHash);

    @Delete("DELETE FROM bt_peer_info WHERE last_announce_time < #{expireTime}")
    int deleteInactivePeers(LocalDateTime expireTime);

}//This is a comment
